package avicit.bdp.lineage.druid.process.tablesource;

import java.util.concurrent.atomic.AtomicInteger;

import avicit.bdp.lineage.druid.anotation.SQLObjectType;
import avicit.bdp.lineage.druid.contants.ParserConstant;
import avicit.bdp.lineage.druid.model.TableNode;
import avicit.bdp.lineage.druid.model.TreeNode;
import avicit.bdp.lineage.druid.process.ProcessorRegister;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.statement.SQLSelectQuery;
import com.alibaba.druid.sql.ast.statement.SQLSubqueryTableSource;
import com.alibaba.druid.sql.ast.statement.SQLTableSource;

/**
 * <p>
 * SQLSubqueryTableSource
 * </p>
 * eg: <p>select t1.a1 from (select a1 from tablex) t1</p>
 *
 */
@SQLObjectType(clazz = SQLSubqueryTableSource.class)
public class SQLSubqueryTableSourceProcessor implements TableSourceProcessor {

    @Override
    public void process(String dbType, AtomicInteger sequence, TreeNode<TableNode> parent,
                        SQLTableSource sqlTableSource) {

        // 建立中间节点 支持子查询的别名
        TableNode proxyTable = TableNode.builder()
                .isVirtualTemp(true)
                .expression(SQLUtils.toSQLString(sqlTableSource))
                .name(ParserConstant.TEMP_TABLE_PREFIX + sequence.incrementAndGet())
                .alias(sqlTableSource.getAlias())
                .build();

        TreeNode<TableNode> proxyNode = TreeNode.of(proxyTable);
        parent.addChild(proxyNode);

        SQLSelectQuery sqlSelectQuery = ((SQLSubqueryTableSource) sqlTableSource).getSelect().getQuery();
        ProcessorRegister.getSQLSelectQueryProcessor(sqlSelectQuery.getClass())
                .process(dbType, sequence, proxyNode, sqlSelectQuery);
    }

}
